<template>
  <div>
    <a-table :columns="columns" :data-source="data"
             :loading="loading" :defaultExpandedRowKeys="[1]"
             :rowKey="record => record.apiId" >
      <template slot="title">
        <a-row type="flex" justify="space-between">
          <a-col :span="4">
            <a-button type="primary" style="margin-left: 10px;" icon="plus-circle" @click="showAddModal()" >
              新增接口
            </a-button>
            <a-modal
                :title="modalForm.title"
                :visible="modalForm.visible"
                :confirm-loading="modalForm.confirmLoading"
                okText="提交"
                cancelText="取消"
                @ok="handleModalOk"
                @cancel="handleModalCancel">
              <a-form-model @submit="handleModalFormSubmit"
                            :label-col="{span:4}" :wrapper-col="{span:14}" ref="addForm"
                            :model="addForm" :rules="modalForm.modalFormRules"  >
                <a-form-model-item label="上级接口" ref="apiPid" prop="apiPid">
                  <a-tree-select
                      v-model="addForm.apiPid"
                      :disabled="modalForm.isDisabled"
                      style="width: 100%"
                      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                      :tree-data="data"
                      placeholder="请选择父节点"
                      :replaceFields="modalForm.selectTreeReplaceFields"
                  >
                  </a-tree-select>
                </a-form-model-item>

                <a-form-model-item label="接口名称" ref="apiName" prop="apiName">
                  <a-input v-model="addForm.apiName" placeholder="接口名称"/>
                </a-form-model-item>

                <a-form-model-item label="接口路径" ref="apiUrl" prop="apiUrl">
                  <a-input v-model="addForm.apiUrl" placeholder="接口路径" />
                </a-form-model-item>

                <a-form-model-item label="接口排序" ref="sort" prop="sort">
                  <a-input-number v-model="addForm.sort" :min="1" :max="50" placeholder="接口排序" />
                </a-form-model-item>

                <a-form-model-item label="是否启用" ref="status" prop="status">
                  <a-radio-group v-model="addForm.status">
                    <a-radio-button value="1">
                      启用
                    </a-radio-button>
                    <a-radio-button value="0">
                      禁用
                    </a-radio-button>
                  </a-radio-group>
                </a-form-model-item>
              </a-form-model>

            </a-modal>
          </a-col>

          <a-col >
            <a-form-model ref="queryForm"
                          layout="inline" :model="formInline">
              <a-form-model-item ref="apiNameLike" prop="apiNameLike">
                <a-input v-model="formInline.apiNameLike" placeholder="模糊查询接口名称">
                </a-input>
              </a-form-model-item>

              <a-form-model-item ref="searchStatus" prop="searchStatus">
                <a-select v-model="formInline.searchStatus" style="width: 200px" placeholder="请选择要查询的接口状态">
                  <a-select-option value="1">
                    启用
                  </a-select-option>
                  <a-select-option value="0">
                    禁用
                  </a-select-option>
                </a-select>
              </a-form-model-item>

                <a-form-model-item>
                  <a-button
                      type="primary"
                      @click="handleSubmit"
                      :disabled="isDisable">
                    查询
                  </a-button>
                  <a-button style="margin-left: 10px;" @click="resetSearchForm('queryForm')">
                    重置
                  </a-button>
                </a-form-model-item>
            </a-form-model>
          </a-col>
        </a-row>
      </template>

      <template #status="status">
        <a-tag :color="status?'green':'volcano'">
          <span v-if="status">启用</span>
          <span v-else>禁用</span>
        </a-tag>
      </template>

      <template #action="record">
        <a-button type="primary" shape="circle" icon="edit" @click="showEditModal(record)" />
        <a-divider type="vertical" />
        <a-popconfirm
            :title="`确认要删除:${record.apiName}吗?`"
            ok-text="确认"
            cancel-text="取消"
            @confirm="handleDeleteApi(record.apiId)"
        >
          <a-icon slot="icon" type="question-circle-o" style="color: red" />
          <a-button type="danger" shape="circle" icon="delete" />
        </a-popconfirm>

      </template>

    </a-table>
  </div>
</template>

<script>
const columns = [
  {
    title: 'ApiId',
    dataIndex: 'apiId',
    key: 'apiId',
  },
  {
    title: '接口名称',
    dataIndex: 'apiName',
    key: 'apiName',
  },
  {
    title: '接口地址',
    dataIndex: 'apiUrl',
    key: 'apiUrl',
  },
  {
    title: '排序',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  }
];

const selectTreeReplaceFields = {
  children:'children',
  title:'apiName',
  key:'apiId',
  value: 'apiId'
}

const modalFormRules = {
  apiPid: [
    {required: true, message: '请选择上级接口',trigger:['blur','change']},
  ],
  apiName: [
    {required: true, message: '请输入接口名称', trigger: ['blur']},
  ],
  apiUrl:[
    {required: false, message: '请输入接口路径', trigger: ['blur']}
  ],
  sort: [
    {required: true, message: '请输入当前接口在同级接口内的排序序号', trigger: 'blur'},
  ],
  status:[
    {required: true, message: '请选择是否启用', trigger: 'change'}
  ]
}

import {getApiTree,addApi,deleteApiById,updateApi} from "@/api/api";
export default {
  name: "SystemApi",
  components: {},
  data() {
    return {
      formInline: {
        apiNameLike: '',
        searchStatus: undefined,
      },
      modalForm:{
        title:'',
        visible:false,
        confirmLoading: false,
        selectTreeReplaceFields,
        modalFormRules,
        isDisabled:false
      },
      addForm:{
        apiId:undefined,
        apiPid:undefined,
        apiName:'',
        apiUrl:'',
        status:undefined,
        sort:undefined
      },
      data:[],
      loading:false,
      columns,
      isHandleSubmit:false,
    }
  },
  mounted() {
    this.getApiTreeData()
  },
  methods:{
    // 查询表单提交
    print(a,b){
      console.log(a,b)
    },
    handleSubmit() {
      console.log(this.formInline)
      this.isHandleSubmit = true;
      let submitParams = {
        rootApiId:1
      }

     if (this.formInline.apiNameLike!==''){
       submitParams['apiNameLike'] = this.formInline.apiNameLike
     }
     if (typeof (this.formInline.searchStatus)!=='undefined'){
       submitParams['apiStatus']=this.formInline.searchStatus==='1'
     }
     console.log('SystemApi handleSubmit',submitParams)
      this.getApiTreeData(submitParams)
    },
    resetSearchForm(formName) {
      this.$refs[formName].resetFields();
      if (this.isHandleSubmit){
        this.getApiTreeData()
      }
    },
    // 获取树形API数据
    getApiTreeData(param= {rootApiId:1}){
      this.loading = true
      getApiTree(param).then(res=>{
        this.data = res.data
      }).catch(err=>{
        console.log("SystemApi:getApiTreeData:"+err.message);
      }).finally(()=>{
        this.loading = false
      })
    },
    // addForm start
    showAddModal(){
      this.modalForm.isDisabled = false;
      this.modalForm.visible =  true
      this.modalForm.title = '新增接口'
    },
    showEditModal(record){
      console.log(record)
      this.modalForm.isDisabled = true
      this.modalForm.visible =  true
      this.modalForm.title = '修改接口'
      let {apiId, apiPid, apiName, apiUrl, status,sort} = record
      this.addForm = {
        apiId,apiPid,apiName,apiUrl,sort,
        status: status?"1":"0"
      }
    },
    // 处理modal里的表单提交
    handleModalOk(){
      this.handleModalFormSubmit()
    },
    handleModalCancel(){
      this.modalForm.visible = false
      this.resetForm('addForm')
    },
    handleModalFormSubmit(){
      this.$refs['addForm'].validate(valid=>{
        if (valid) {
          let submitData = this.addForm
          submitData.status = this.addForm.status === "1"
          this.modalForm.confirmLoading = true
          if (this.modalForm.isDisabled){
            this.handleUpdateApi(submitData)
          }else {
            this.handleAddApi(submitData)
          }
        } else {
          this.handleFiled(new Error('表单校验不通过'))
          return false;
        }
      })
    },
    resetForm(formName) {
      this.addForm = {
            apiId:undefined,
            apiPid:undefined,
            apiName:'',
            apiUrl:'',
            status:undefined,
            sort:undefined
      }
      this.$refs[formName].resetFields();
    },
    // addForm end
    handleAddApi(api){
      addApi(api).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleDeleteApi(apiId){
      deleteApiById(apiId).then(res=>{
        this.handleSuccess(res)
      }).catch(err=> this.handleFiled(err))
    },
    handleUpdateApi(api){
      updateApi(api).then(res=>{
        this.handleSuccess(res)
        this.resetForm('addForm')
      }).catch(err=> this.handleFiled(err))
    },
    handleSuccess(res){
      this.modalForm.confirmLoading = false
      this.$notification['success']({
        message: '成功',
        description: `${res.data}`,
        duration: 4
      })
      this.getApiTreeData()
    },
    handleFiled(err){
      this.modalForm.confirmLoading = false
      console.log(err.message)
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).message || {}).message||err.message || '请求出现错误，请稍后再试',
        duration: 4
      })
    }
  },

  computed:{
    isDisable(){
      return this.formInline.apiNameLike===''&&!this.formInline.searchStatus;
    }
  }

}
</script>

<style scoped>

</style>
